package mobileann.mafamily.utils;

import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;

import com.mofind.android.base.L;

import android.R.integer;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;

/**
 * 功能:进行加密解密的工具类
 * @annotation Adrian.20151102
 */
public class TripleDESUtil {
	private static final String TAG = "TripleDESUtil";
	private static final String METHOD = "DESEDE";
	private static final String MODE_CBC = "DESEDE/CBC/NoPadding";
	//	private static final String MODE_ECB = "DESEDE/ECB/NoPadding";
	/**
	 * 加密
	 * @param encodeData
	 * @return
	 */
	public static String CBCEncode(String uid,String random,String encodeData){
		String result = "";
		try {
			String datas = URLEncoder.encode(encodeData,"UTF-8");
			byte[] data = bytesEnTrans(datas.getBytes("UTF-8"));
			byte[] key = getKeyBytes(uid,random);
			byte[] keyiv = getIVBytes(uid,random);
			byte[] bCBCEnStr = des3EncodeCBC(key, keyiv, data);
			result = Base64.encodeToString(bCBCEnStr, Base64.NO_WRAP);
		} catch (Exception e) {
			L.e("maf", "error--", e);
		}
		return result;
	}

	/**
	 * 解密获取字符串
	 * @param decodeData
	 * @return
	 */
	public static String CBCDecode(String uid,String random,String decodeData){
		String result = "";
		try {
			byte[] datas = Base64.decode(decodeData, Base64.NO_WRAP);
			byte[] key = getKeyBytes(uid,random);
			byte[] keyiv = getIVBytes(uid,random);
			byte[] bCBCDeStr = des3DecodeCBC(key, keyiv, datas);
			result = URLDecoder.decode(new String(bCBCDeStr, "UTF-8"), "UTF-8");
//			String res2 = resTemp.substring(0, resTemp.lastIndexOf('}')+1);
//			result = decode(res2);
		} catch (Exception e) {
			L.e("maf", "error--", e);
		}
		return result;
	}
	
	public static String getJsonObjStr(String uid,String random,String decodeData){
		String result = CBCDecode(uid,random,decodeData);
		if(TextUtils.isEmpty(result)){
			return "";
		}else{
			return result.substring(0, result.lastIndexOf('}')+1);
		}
	}
	
	public static String getJsonArrStr(String uid,String random,String decodeData){
		String result = CBCDecode(uid,random,decodeData);
		if(TextUtils.isEmpty(result)){
			return "";
		}else{
			return result.substring(0, result.lastIndexOf(']')+1);
		}
	}
	
//	private static String getSourceKey(){
//		String uid = testUID;
//		String random = testIRAD;
//		String sourceKey = uid+ (uid+random).length()+random;
//		return sourceKey;
//	}
	private static String getSourceKey2(String uid,String random){
		String temp = Long.parseLong(uid) * uid.length() + random;
		String middle = MD5.getMD5(temp.getBytes());
		String sourceKey = uid + middle + random;
		return sourceKey;
	}
	
	private static byte[] getKeyBytes(String uid,String random){
		String sourceKey = getSourceKey2(uid,random);
		String secretKey =  MD5.getMD5(sourceKey.getBytes());
		byte[] key = Base64.decode(secretKey, Base64.NO_WRAP);
		return key;
	}
	private static byte[] getIVBytes(String uid,String random){
		byte[] keyiv = null;
		try {
			String sourceKey = getSourceKey2(uid,random);
			String iv = sourceKey.substring(sourceKey.length()-8, sourceKey.length());
			keyiv = iv.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			L.e("maf", "error--", e);
		}
		return keyiv;
	}

	private static byte[] bytesEnTrans(byte[] src){
		int srcLen = src.length;
		int dstLen = srcLen + 8 - srcLen % 8;
		byte[] dst = new byte[dstLen];
		System.arraycopy(src, 0, dst, 0, srcLen);
		return dst;
	}

	/**
	 * 处理unicode码与其他字符串混合的字符串
	 * @param unicodeStr
	 * @return
	 */
	public static String decodeUnicode(String unicodeStr) {
		if (unicodeStr == null) {
			return null;
		}
		StringBuffer retBuf = new StringBuffer();
		int maxLoop = unicodeStr.length();
		for (int i = 0; i < maxLoop; i++) {
			if (unicodeStr.charAt(i) == '\\') {
				if ((i < maxLoop - 5)
						&& ((unicodeStr.charAt(i + 1) == 'u')
								|| (unicodeStr.charAt(i + 1) == 'U')))
					try {
						retBuf.append((char) Integer.parseInt(
								unicodeStr.substring(i + 2, i + 6), 16));
						i += 5;
					} catch (NumberFormatException localNumberFormatException) {
						retBuf.append(unicodeStr.charAt(i));
					}
				else
					retBuf.append(unicodeStr.charAt(i));
			} else {
				retBuf.append(unicodeStr.charAt(i));
			}
		}
		return retBuf.toString();
	}

	/**
	 * CBC加密
	 * @param key 密钥
	 * @param keyiv IV
	 * @param data 明文
	 * @return 密文
	 * @throws Exception
	 */
	private static byte[] des3EncodeCBC(byte[] key, byte[] keyiv, byte[] data)
			throws Exception {
		SecretKey deskey = null ;
		DESedeKeySpec spec = new DESedeKeySpec(key);
		SecretKeyFactory keyfactory = SecretKeyFactory.getInstance(METHOD);
		deskey = keyfactory.generateSecret(spec);
		Cipher cipher = Cipher.getInstance(MODE_CBC);
		IvParameterSpec ips = new IvParameterSpec(keyiv);
		cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
		byte[] bOut = cipher.doFinal(data);
		return bOut;
	}

	/**
	 * CBC解密
	 * @param key 密钥
	 * @param keyiv IV
	 * @param data Base64编码的密文
	 * @return 明文
	 * @throws Exception
	 */
	private static byte[] des3DecodeCBC(byte[] key, byte[] keyiv, byte[] data)
			throws Exception {
		SecretKey deskey = null ;
		DESedeKeySpec spec = new DESedeKeySpec(key);
		SecretKeyFactory keyfactory = SecretKeyFactory.getInstance(METHOD);
		deskey = keyfactory.generateSecret(spec);
		Cipher cipher = Cipher.getInstance(MODE_CBC);
		IvParameterSpec ips = new IvParameterSpec(keyiv);
		cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
		byte[] bOut = cipher.doFinal(data);
		return bOut;
	}

	/**
	 * ECB加密,不要IV
	 * @param key 密钥
	 * @param data 明文
	 * @return 密文
	 * @throws Exception
	 */
	//	private static byte[] des3EncodeECB(byte[] key, byte[] data)
	//			throws Exception {
	//		SecretKey deskey = null ;
	//		DESedeKeySpec spec = new DESedeKeySpec(key);
	//		SecretKeyFactory keyfactory = SecretKeyFactory.getInstance(METHOD);
	//		deskey = keyfactory.generateSecret(spec);
	//		Cipher cipher = Cipher.getInstance(MODE_ECB);
	//		cipher.init(Cipher.ENCRYPT_MODE, deskey);
	//		byte[] bOut = cipher.doFinal(data);
	//		return bOut;
	//	}

	/**
	 * ECB解密,不要IV
	 * @param key 密钥
	 * @param data Base64编码的密文
	 * @return 明文
	 * @throws Exception
	 */
	//	private static byte[] des3DecodeECB(byte[] key, byte[] data)
	//			throws Exception {
	//		SecretKey deskey = null ;
	//		DESedeKeySpec spec = new DESedeKeySpec(key);
	//		SecretKeyFactory keyfactory = SecretKeyFactory.getInstance(METHOD);
	//		deskey = keyfactory.generateSecret(spec);
	//		Cipher cipher = Cipher.getInstance(MODE_ECB);
	//		cipher.init(Cipher.DECRYPT_MODE, deskey);
	//		byte[] bOut = cipher.doFinal(data);
	//		return bOut;
	//	}
}
